package com.lftea.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.ICustomerDAO;
import com.lftea.po.Customer;
import com.lftea.util.StringUtils;

@Repository("customerDAOImpl")
public class CustomerDAOImpl implements ICustomerDAO {

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public List<Customer> findAll() {
		String sql = "select * from Customer";
		return jdbcTemplate.query(sql, new CustomerMapper());
	}

	public Customer findById(long customerId) {
		String sql = "select * from Customer where Customer_ID=?";
		return (Customer) jdbcTemplate.query(sql, new Object[] { customerId },
				new CustomerMapper());
	}

	public void remove(Customer customer) {
		long customerId = customer.getId();
		String sql = "delete Customer where Customer_ID=?";
		jdbcTemplate.update(sql, new Object[] { customerId });
	}

	public void save(Customer customer) {
		long customerId = customer.getId();
		String name = StringUtils.toISO(customer.getName());
		String phone = customer.getPhone();
		String mobile = customer.getMobile();
		String address = StringUtils.toISO(customer.getAddress());
		String email = customer.getEmail();
		String remark = StringUtils.toISO(customer.getRemark());

		String sql = "select count(*) from Customer where Customer_ID=?";
		int result = jdbcTemplate.queryForInt(sql, new Object[] { customerId });
		Object[] params = null;
		if (result > 0) {
			sql = "update Customer set name=?,phone=?,mobile=?,address=?,email=?,remark=? where Customer_ID=?";
			params = new Object[] { name, phone, mobile, address, email,
					remark, customerId };
		} else {
			sql = "insert into Customer(name,phone,mobile,address,email,remark) values(?,?,?,?,?,?)";
			params = new Object[] { name, phone, mobile, address,
					email, remark };
		}
		jdbcTemplate.update(sql, params);
	}

	private static final class CustomerMapper implements RowMapper<Customer> {

		public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
			Customer customer = new Customer();
			customer.setId(rs.getLong("Customer_ID"));
			customer.setName(StringUtils.toGBK(rs.getString("name")));
			customer.setPhone(rs.getString("phone"));
			customer.setMobile(rs.getString("mobile"));
			customer.setAddress(StringUtils.toGBK(rs.getString("address")));
			customer.setEmail(rs.getString("email"));
			customer.setRemark(StringUtils.toGBK(rs.getString("remark")));
			return customer;
		}

	}
}
